package org.learn.spring_quartz.job;

import lombok.extern.slf4j.Slf4j;
import org.learn.spring_quartz.bean.WebClientConfig;
import org.learn.spring_quartz.dto.QueryParams;
import org.learn.spring_quartz.dto.RequestData;
import org.learn.spring_quartz.dto.Result;
import org.learn.spring_quartz.dto.User;
import org.learn.spring_quartz.service.ApiService;
import org.quartz.*;
import org.quartz.impl.calendar.HolidayCalendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Slf4j
@Component
public class WebJob implements Job {

    @Autowired
    private WebClientConfig webClientConfig;

    @Autowired
    private ApiService apiService;

    @Autowired
    private Scheduler scheduler;  // 注入 Scheduler 获取 Calendar

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        doJob(jobExecutionContext);
        // 获取 HolidayCalendar
        HolidayCalendar holidayCalendar = null;
        try {
            holidayCalendar = (HolidayCalendar) jobExecutionContext.getScheduler().getCalendar("holidays");
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }

        // 判断今天是否节假日
        LocalDate today = LocalDate.now();
        Date todayDate = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());

        if (!holidayCalendar.isTimeIncluded(todayDate.getTime())) {
            System.out.println("今天是节假日，任务跳过");
            return;  // 节假日直接跳过
        }
        log.info("进入了定时任务");
        doJob(jobExecutionContext);
    }

    private void doJob(JobExecutionContext jobExecutionContext){
        String url = jobExecutionContext.getJobDetail().getJobDataMap().getString("url")+"/login";
        try{

            Result result = getUser();
            if(result.getCode() != 1){
                Result resultToken = getToken();
                webClientConfig.updateToken((String) resultToken.getData());
                result = getUser();
            }
            log.info("请求成功: {}, 响应内容: {}", url, result);
        } catch (Exception e) {
            if(e.getMessage().contains("401")){
                Result resultToken = getToken();
                webClientConfig.updateToken((String) resultToken.getData());
                Result result = getUser();
                log.info("请求成功: {}, 响应内容: {}", url, result);
            }
            log.error("请求失败: {}", url, e);
        }
    }

    /**
     * 获取token
     * @return
     */
    private Result getToken(){
        RequestData admin = new RequestData("/login", new User("admin", "0192023a7bbd73250516f069df18b500"));
        return apiService.postData(admin);
    }

    private Result getUser(){
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        QueryParams queryParams = new QueryParams("/users", map);
        return apiService.fetchData(queryParams);
    }


}
